<?php


namespace app\api\controller;

use EasyWeChat\Factory;
use app\api\model\WxMessage;
use think\Cache;
use think\Db;

class Wxevent
{

    public function index()
    {


        $config = [
            'app_id' => config("wechat.appid"),
            'secret' => config("wechat.secret"),
            'token' => 'MGvhTfbBLbAKSSoLzgl',
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array'
            //...
        ];

        $app = Factory::officialAccount($config);
        log_print($config);

//        $message = [
//            'FromUserName' =>'oJDVt5b3cxza-6Vs5cgVdLlFNhvo',
//            'MsgType'=>'event'
//        ]

        $app->server->push(function ($message) {
            log_print($message);
            if($message['MsgType'] == 'event'){
                if($message['Event'] == 'subscribe' || $message['Event'] == 'SCAN'){
                    log_print($message);
                    if($message['Event'] == 'subscribe'){
                        $order_id = substr($message['EventKey'],8);
                    }else{
                        $order_id = $message['EventKey'];
                    }

                    if(!empty($order_id)){
                        $order_info = Db::name('appointment_order')->where('id',$order_id)->find();

                        if(!empty($order_info)){
                            $type = Db::name('appointment_type')->where(['type_id'=>$order_info['type_id']])->value('name');
                        }else{
                            $type = '家政服务';
                        }
                        $param = [
                            'openid'=>$message['FromUserName'],
                            'type'=>$type,
                            'order_id'=>$order_id
                        ];

                        WxMessage::sendMessage(4,$param);

                        return;
                    }


                }

//                return "您好！欢迎使用 EasyWeChat";

//                $user = Db::name('user')->where(['open_id'=>$message['FromUserName']])->find();

                $order_id = Cache::get($message['FromUserName'].'_order_id');

                if(!empty($order_id)){
                    $order_info = Db::name('appointment_order')->where('order_id',$order_id)->find();

                    if(!empty($order_info)){
                        $type = Db::name('appointment_type')->where(['type_id'=>$order_info['type_id']])->value('name');
                    }else{
                        $type = '家政服务';
                    }
                    $param = [
                        'openid'=>$message['FromUserName'],
                        'type'=>$type,
                        'order_id'=>$order_id
                    ];

                    log_print($param);
                    WxMessage::sendMessage(4,$param);

                }


            }

            return;

            //return $message['FromUserName'].'_order_id';

        });

        $response = $app->server->serve();

        // 将响应输出
        $response->send();exit; // Laravel 里请使用：return $response;



        $app = Factory::officialAccount($config);


    }


    /*
    * 公众号携带参数
    */
    public function QRCode()
    {
        $order_id = input('order_id');

        $app = Factory::officialAccount(config("wechat_easy"));

        $accessToken = $app->access_token;

        $token = $accessToken->getToken();

        $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=' . $token['access_token'];

        $params = [
            'expire_seconds' =>    60488,
            'action_name'   => 'QR_SCENE',
            'action_info'   => [
                'scene' => ['scene_id'=>$order_id]
            ]
        ];

        $response = posturl($url, $params);
        if($response['ticket']){
            $url = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.urlencode($response['ticket']);
            $code = doCurlGetRequest($url);
            $path = 'uploads/code/' . date('Ymd') . '/';
            if (!is_dir($path)) mkdir($path, 0777, true);
            $file = $path . 'qr' . $order_id . '_' . time() . '.png';

            file_put_contents($file, $code);
            $url = base_url().'/' . $file;
            $data = [
                'code'=>1,
                'url'=>$url
            ];
            return json($data);
        }
    }

}